package com.qingyun.web.controller.pcapi.shop;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qingyun.common.annotation.RepeatSubmit;
import com.qingyun.common.core.domain.AjaxResult;
import com.qingyun.common.core.page.TableDataInfo;
import com.qingyun.common.core.validate.AddGroup;
import com.qingyun.common.core.validate.EditGroup;
import com.qingyun.common.utils.poi.ExcelUtil;
import com.qingyun.security.controller.BaseController;
import com.qingyun.security.utils.SecurityUtils;
import com.qingyun.shop.domain.TiktokActivity;
import com.qingyun.shop.domain.TiktokCoupon;
import com.qingyun.shop.domain.TiktokShopDocument;
import com.qingyun.shop.domain.bo.TiktokActivityBo;
import com.qingyun.shop.domain.vo.TiktokActivityVo;
import com.qingyun.shop.service.ITiktokActivityService;
import com.qingyun.shop.service.ITiktokCouponService;
import com.qingyun.shop.service.ITiktokShopDocumentService;
import com.qingyun.tiktok.config.DyConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 优惠券活动Controller
 *
 * @author qingyun
 * @date 2021-09-04
 */
@Validated
@Api(value = "优惠券活动控制器", tags = {"^优惠券活动管理"})
@AllArgsConstructor
@RestController
@RequestMapping("/shop/activity")
public class TiktokActivityController extends BaseController {

    private final ITiktokActivityService iTiktokActivityService;

    private final ITiktokCouponService iTiktokCouponService;

    private final ITiktokShopDocumentService shopDocumentService;

    private DyConfig dyConfig;
    /**
     * 查询优惠券活动列表
     */
    @ApiOperation("查询优惠券活动列表 shop:activity:list")
    @PreAuthorize("@ss.hasPermi('shop:activity:list')")
    @GetMapping("/list")
    public TableDataInfo<TiktokActivityVo> list(@Validated TiktokActivityBo bo) {

        return iTiktokActivityService.queryPageList(bo);
    }

    /**
     * 导出优惠券活动列表
     */
    @ApiOperation("导出优惠券活动列表 shop:activity:export")
    @PreAuthorize("@ss.hasPermi('shop:activity:export')")
    @GetMapping("/export")
    public void export(@Validated TiktokActivityBo bo, HttpServletResponse response) {
        List<TiktokActivityVo> list = iTiktokActivityService.queryList(bo);
        ExcelUtil.exportExcel(list, "优惠券活动", TiktokActivityVo.class, response);
    }

    /**
     * 获取优惠券活动详细信息
     */
    @ApiOperation("获取优惠券活动详细信息 shop:activity:query")
    @PreAuthorize("@ss.hasPermi('shop:activity:query')")
    @GetMapping("/{id}")
    public AjaxResult<TiktokActivityVo> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        return AjaxResult.success(iTiktokActivityService.queryById(id));
    }

    /**
     * 新增优惠券活动
     */
    @ApiOperation("新增优惠券活动 shop:activity:add")
    @PreAuthorize("@ss.hasPermi('shop:activity:add')")
    @RepeatSubmit()
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TiktokActivityBo bo) {
        return toAjax(iTiktokActivityService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改优惠券活动
     */
    @ApiOperation("修改优惠券活动 shop:activity:edit")
    @PreAuthorize("@ss.hasPermi('shop:activity:edit')")
    @RepeatSubmit()
    @PutMapping()
	@CacheEvict(cacheNames = "selectCoupon", key = "#bo.id")
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TiktokActivityBo bo) {
        return toAjax(iTiktokActivityService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除优惠券活动(禁用)
     */
    @ApiOperation("删除优惠券活动 shop:activity:remove")
    @PreAuthorize("@ss.hasPermi('shop:activity:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")
                                       @PathVariable Long[] ids) {
        return toAjax(iTiktokActivityService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @ApiOperation("修改活动状态")
	@PreAuthorize("@ss.hasPermi('shop:activity:edit')")
    @PutMapping("updateStatus")
    public AjaxResult updateStatus(Long activityId,Long status){
		TiktokActivity activity = iTiktokActivityService.getById(activityId);
		if (activity.getEndDate().before(new Date())) {
			return AjaxResult.error("此活动已经过期，请重新修改活动有效期限");
		}
		activity.setStatus(status);
		boolean update = iTiktokActivityService.updateById(activity);
		return toAjax(update);
	}


    @ApiOperation("查看活动二维码")
    @GetMapping("/getActivityQrcode")
    public AjaxResult activityQrcode(Long activityId){
		TiktokActivityVo tiktokActivityVo = iTiktokActivityService.queryById(activityId);
		if (ObjectUtil.isNull(tiktokActivityVo)) {
			return AjaxResult.error("活动不存在");
		}
		StringBuilder builder = new StringBuilder();
		builder.append("https://open.douyin.com/platform/oauth/connect/?client_key=");
		builder.append(dyConfig.getAppId());
		builder.append("&response_type=code&scope=trial.whitelist,user_info,video.data,fans.check,item.comment&redirect_uri=");
		builder.append(dyConfig.getUserRedirectUri() + "?activityId=" + activityId);
		return AjaxResult.success(builder.toString());
	}

	@ApiOperation("获取商户优惠卷列表")
	@GetMapping("/activityShopCoupons")
	public AjaxResult shopCoupons(Long shopId){
    	Long spId=null;
    	 if(!SecurityUtils.isManager()){
    	 	spId=SecurityUtils.getShop().getId();
		 }else{
			 if (shopId==null) {
				 return AjaxResult.error("商户id不能为空");
			 }
    	 	spId=shopId;
		 }
		List<TiktokCoupon> list = iTiktokCouponService.list(Wrappers.lambdaQuery(TiktokCoupon.class)
			.eq(TiktokCoupon::getShopId, spId)
			.eq(TiktokCoupon::getStatus, 1)
		    .orderByDesc(TiktokCoupon::getId)
		);
		return AjaxResult.success(list);
	}

	@ApiOperation("判断是否有文案")
	@GetMapping("/isWriting")
	public AjaxResult isWriting(Long shopId){
    	if(SecurityUtils.isManager()){
			if (ObjectUtil.isNull(shopId)) {
				return AjaxResult.error("请携带商户id");
			}
		}else{
			shopId=SecurityUtils.getShop().getId();
		}
		int count = shopDocumentService.count(Wrappers.lambdaQuery(TiktokShopDocument.class).eq(TiktokShopDocument::getShopId,shopId));
		if (count>0) {
			return AjaxResult.success(true);
		}

		return AjaxResult.success(false);
	}

}
